/*
@STI LICENSE
(C) 2006-2008 Universit�t Innsbruck.

This file is part of myOntology.

myOntologyis free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

myOntologyis distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with myOntology.  If not, see <http://www.gnu.org/licenses/>.

@STI LICENSE */
package view.HTMLUIcomponents;

import java.util.ArrayList;
import java.util.Iterator;

import model.DHTMLConstants;
import model.Labels;
import model.Vocabulary;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.log4j.Logger;
import org.openrdf.model.URI;

import controller.HelperFunctions;
import controller.elementMapper.Mapper;
import controller.elementMapper.OntologyModuleMapper;
import controller.elementMapper.StoredInMeantimeException;
import controller.elementMapper.UriAlreadyExistsException;
import controller.elementMapper.VersioningMapper;
import controller.elementMapper.WrongFormatException;
import controller.sesameDataConnector.AbstractDataConnector;


public abstract class AbstractComponent {

	public static Logger logger = Logger.getLogger(AbstractComponent.class);
	
	private static final String CSSCLASSFIELD = "elementfield";
	private static final String CSSCLASSCONTENT = "fieldcontent";
	private static final String CSSCLASSTITLE = "fieldtitle";
	
	public static final String NAMEFORMELEMENTADDEREXTENSION = "_adder";

	public static final String NOTHINGSELECTED = "-";
	
	protected static String WordNetDirectory = null;
	
	public static void setWordNetDirectory( String entry ) {
		WordNetDirectory = entry;
	}	
	public static boolean isWordNetDirectorySet() {
		return (WordNetDirectory!=null);
	}
	public static String getWordNetDirectory() {
		return WordNetDirectory;
	}

	protected static String getFieldContainer( String content, String divname ) {
		String ret = "";

		ret += "<div class=\"" + CSSCLASSFIELD + "\" id=\"" + divname + "\">\n";
		ret += content;
		ret += "</div>\n\n";
		
		return ret;
	}
	
	public static String getEmptyFieldContainer( String cssidfield) {

		String ret = "";
		
		ret += "<div class=\"\" id=\"" + cssidfield + "\"></div>";
		
		return ret;
	}
	
	protected static String getFormContainer( String content, String cssid ) {
		
		String ret = "";

		ret += "<div class=\"" + CSSCLASSCONTENT + "\" id=\"" + cssid + "\">\n";
		ret += content;
		ret += "</div>\n";
		
		return ret;
	}
	


	protected static String getTitleContainer( model.Label field, boolean required, boolean plural ) {
		
		return getTitleContainer( field, null, required, plural );
	}
		

	protected static String getTitleContainer( model.Label field, String viewType, boolean required, boolean plural ) {
		
		String ret = "";

		
		if( plural == true )
			ret = field.getNamePlural();
		else
			ret = field.getNameSingular();
		

		String note = "";
		if( !field.getComment().equals( "" ) ) {
			note += field.getComment() + "<br/>";
		}
		if( !field.getSynonyms().equals( "" ) ) {
			note += "Synonyms for this field: " + field.getSynonyms();
		}			
		
		if( !note.equals("") ) {
			ret += controller.HelperFunctions.getNotification( note );
		}

		if( required == true ) {
			ret += " " + controller.HelperFunctions.getWarning( "This is an essential field!" );
		}
		
		return getTitleContainer( ret, viewType );
	}
	
	protected static String getTitleContainer( String title, String viewType ) {
		
		String ret = "";
		

		String h3class = viewType;

		ret += "<h3 class=\"" + CSSCLASSTITLE + " " + h3class + "\">";

		ret += title;

		ret += "</h3>\n";
		
		return ret;
	}
	
	// ####################################################################################

	protected static String getLinkToShowSecondaryFieldInEditMode( String cssidcontent, boolean shownavigationInEditField, String linkedWord ) {

		String ret = "";
		
		ret += 
			"<div id=\"" + cssidcontent + "_formopener\">" +
			//	"<img onmouseover=\"this.style.cursor='pointer'\" onclick=\"javascript:this.src='skins/default/images/loading.gif';this.onmouseover=\'\';this.style.cursor='wait';showcontentineditmode('" + cssidcontent +"'," + (shownavigationInEditField? "true" : "false") + ");\" src=\"skins/default/images/pencil.png\" border=\"0\" title=\"Edit\" alt=\"Edit\" />" + linkedWord + "" +
				"<img style=\"cursor:pointer;\" onclick=\"this.src='skins/default/images/loading.gif';this.onmouseover=\'\';this.style.cursor='wait';showcontentineditmode('" + cssidcontent +"'," + (shownavigationInEditField? "true" : "false") + ");document.getElementById('" + cssidcontent + "_formopener').innerHTML='';\" src=\"skins/default/images/pencil.png\" border=\"0\" title=\"Edit\" alt=\"Edit\" />" + linkedWord + "" +
			"</div>\n";
		
		return ret;
	}
	
	

	protected static String getLinkToEditfield( String cssidcontent, String entry, boolean shownavigationInEditField, String viewType ) {

		String ret = "";
		
		String escapedEntry = "";
		
		if( entry!=null )
			escapedEntry = StringEscapeUtils.escapeJavaScript( StringEscapeUtils.escapeHtml( entry ) );
		
		if( escapedEntry.contains("#"))
			escapedEntry = escapedEntry.replace( "#", "%23" );
		
		ret += "<img style=\"cursor:pointer\" onclick=\"this.src='skins/default/images/loading.gif';this.onmouseover=\'\';this.style.cursor='wait';showformineditmode('" + cssidcontent +"','" + escapedEntry + "'," + (shownavigationInEditField? "true" : "false") + ",'" + viewType + "');\" src=\"skins/default/images/pencil.png\" border=\"0\" title=\"Edit\" alt=\"Edit\" />";
		
		return ret;
	}
	
	protected static String getLinkToEditfield( String cssidcontent, String entry, boolean shownavigationInEditField ) {

		String ret = getLinkToEditfield(cssidcontent, entry, shownavigationInEditField, "" );
		
		return ret;
	}
	

	protected static String getLinkToUpdate( String cssidcontent, String nameformalement, String entry ) {
		
		String escapedEntry = "";
		
		if( entry!=null )
			escapedEntry = StringEscapeUtils.escapeJavaScript( StringEscapeUtils.escapeHtml( entry ) );
		
		String ret = "<img style=\"cursor:pointer\" onclick=\"sendupdaterequest('" + cssidcontent +"','"+nameformalement+"','"+escapedEntry+"');\" src=\"skins/default/images/accept.png\" border=\"0\" title=\"Save and close\" alt=\"Save and close\" id=\"" + nameformalement + "_savebutton\" />";

		return ret;
	}
	protected static String getLinkToClose( String cssidcontent ) {
		
		String ret = "<img style=\"cursor:pointer\" onclick=\"this.src='skins/default/images/loading.gif';this.style.cursor='wait';showforminviewmode('" + cssidcontent +"');\" src=\"skins/default/images/cancel.png\" border=\"0\" title=\"Cancel\" alt=\"Cancel\" />";

		return ret;
	}
	
	/*
	private static String getErrors( ArrayList<String> errors ) {

		String ret = "";

		if( errors!=null ) {
			
			Iterator<String> iter = errors.iterator();
			while( iter.hasNext() ) {
				String error = iter.next();
				if( !error.equals("") ) {
					ret += "<div class=\"error\">" + error + "</div>\n";
				}
			}
		}
		
		return ret;
	}
	*/

	/**
	 * 
	 * @param content
	 * @param entry	value as it will send from client to server (So Server gets to know which entry the User wants to edit)
	 * @param id	The id of the element
	 * @param cssidcontent	The id of the css-field, which contains the HTML-content (=entry surrounding with other tags)
	 * @param nameformelement	The name of the hidden field which contains the entry. (The entry is send from client to server)
	 * @param showNavigation
	 * @return
	 */
	protected static String renderViewForm( String content, String entry, String cssidcontent, boolean showNavigation, boolean showNavigationInEditForm ) {
		
		return renderViewForm(content, entry, cssidcontent, showNavigation, showNavigationInEditForm, false, "" );
	}

	protected static String renderViewForm( String content, String entry, String cssidcontent, boolean showNavigation, boolean showNavigationInEditForm, boolean showCreateLinksInEditForm ) {
		
		return renderViewForm(content, entry, cssidcontent, showNavigation, showNavigationInEditForm, showCreateLinksInEditForm, "");		
	}


	protected static String renderViewForm( String content, String entry, String cssidcontent, boolean showNavigation, boolean showNavigationInEditForm, boolean showCreateLinksInEditForm, String viewType ) {

		String ret = "";

		ret +="<table style=\"width:100%;\"><tr>";
		ret += "<td class=\"fieldnavigation\">\n";
		
		if( showNavigation ) { 
			ret += getLinkToEditfield( cssidcontent, entry, showNavigationInEditForm, viewType );
		}
		ret +="</td>\n";
		ret += "<td class=\"fieldcontentcontainer\">\n";
		
		ret += "<div class=\"fieldcontentmain\">\n";
		ret += content;		
		ret += "</div>\n";		

		ret += "</td>\n";
		ret += "</tr></table>\n";
		
		return ret;
	}
		


	

	/**
	 * Creates a field which enables to edit the entry. It shows the errors and shows links to update the entry.
	 * @param content
	 * @param entry	The entry how it would be sent from client to server; The entry which should be edited.
	 * @param errors	ArrayList of errors
	 * @param actualVersionForm	 
	 * @param actualVersionEntry	The entry how it would be sent from client to server to check if it is changed
	 * @param id	The id of the element (http://...)
	 * @param cssidcontent	The id of the css-container which contains the whole form (after update it could be replaced with the view)
	 * @param nameformalement	The name of the HTML-form-element which contains the value which is send from client to server after editing it
	 * @param showNavigation	If the links to update the field should be shown
	 * @return	HTML-Code
	 */
	protected static String renderEditForm( model.Label field, String content, ArrayList<Exception> exceptions, String actualVersionContent, String actualTimestamp, String cssidcontent, String nameformalement, boolean showNavigation ) throws Exception {
		
		String ret = "";
		
		if( field!=null && !field.getComment().equals("")) {
			ret += "<div class=\"fieldexplaination\">(" + StringEscapeUtils.escapeHtml( field.getComment() ) + ")</div>";
		}

		ret +="<table style=\"width:100%;\"><tr>\n";
		ret += "<td class=\"fieldnavigation\">\n";
		
		if( showNavigation ) {
			ret += 

				"<span style=\"margin-right:7px;\">"+
				getLinkToUpdate( cssidcontent, nameformalement, actualTimestamp ) + 
				"</span>" +
				getLinkToClose( cssidcontent );
		}

		ret +="</td>\n";
		ret += "<td class=\"fieldcontentcontainer\">\n";
		
		boolean showActualValues = false;


		String errorsDiv =	
			"<div id=\"" + nameformalement + "_errors\">\n";
		String storedInMeantimeError = "";
		if( exceptions!=null ) {
			
			Iterator<Exception> iter = exceptions.iterator();
			while( iter.hasNext() ) {
				
				Exception exception = iter.next();
							
				if( 
						exception instanceof WrongFormatException || 
						exception instanceof UriAlreadyExistsException ) { //  exception.getMessage()!=null ) {
					
					errorsDiv += "<div class=\"error\">" + exception.getMessage() + "</div>";
				}
				else if( exception instanceof StoredInMeantimeException ) {
					storedInMeantimeError = "<div class=\"error\">" + exception.getMessage() + "</div>";
					showActualValues = true;
				}
				else {
					errorsDiv += "<div class=\"error\">An unknown exception occured. If you want to help to improve myOntology please contact the webmaster and tell how this exception occured.";
					errorsDiv += exception.getMessage() + "</div>";
				}
				
			}
		}
		errorsDiv += 	
			"</div>\n";
		
		ret += storedInMeantimeError + errorsDiv;

		if( showActualValues==true ) {
						
			ret += "<div class=\"alreadystoredheader\">Stored:</div>\n";
			ret += "<div class=\"inputhint\">(Cancel to keep this entry)</div>\n";

			ret += "<div class=\"fieldcontentmain\">\n";
			ret += actualVersionContent;
			ret += "</div>\n";
			
			ret += "<div class=\"alreadystoredheader\">Your Input:</div>\n";
			ret += "<div class=\"inputhint\">(Save to override stored entry)</div>\n";
		}


		ret += "<div class=\"fieldcontentmain\">\n";
		ret += content;
		ret += "</div>\n";

		ret += "</td>\n";
		ret += "</tr></table>\n";
		
		return ret;
	}
	


	/**
	 * returns HTML-code containing a selectBox f�r belongsToOM, Domain, Range
	 * @param elementName	The Name of the field, where the selected Items can be queried out of request.getParameterByName(...)
	 * @param elementEntry	List of preselected elements separated by a comma ("element1,element2,")
	 * @param selectableItems	Arraylist containing the ID and the Label of all Elements which can be selected.
	 * @param ajaxActionCode	indicated, which elements can be selected
	 * @return
	 *//*
	protected static String getSelectBoxReduceableByOM( String nameFormElement, String elementEntry, int ajaxActionCode ) throws Exception {
				
		String ret = "";
		
		
		
		ret +=
			"<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"1\">\n"+
			"	<tr>\n"+
			"		<td>Selected:<br /></td>\n"+
			"		<td></td>\n"+
			"		<td>Items:<br /></td>\n"+
			"	</tr>\n"+
			"	<tr>\n"+
			"		<td valign=\"top\">\n" +
			"			<select size=\"9\" multiple=\"multiple\" name=\"" + nameFormElement + "_list\" class=\"leftselectbox\" >\n";
		

		// the actual values
		String[] strarray = elementEntry.split( HelperFunctions.DEFAULTPLITTER );
		for( int i = 0; i<strarray.length; i++ ){
			
			if( !strarray[i].equals("") ) {
				URI u = new URIImpl(strarray[i]);

				ret+=
					"				<option value=\"" + strarray[i] + "\">" + Mapper.selectLabel( u, Vocabulary.ENGLISH) + "</option>\n";
				
			}
	
		}

		
		ret +=
			"			</select>\n" +
			"		</td>\n"+
			"		<td valign=\"top\"><a href=\"\" onClick=\"setFormValueManipulate('" + nameFormElement + "','Remove'); return false\"><img src=\"skins/default/images/garbage.gif\" style=\"margin-right:10px; border:none;\" onmouseover=\"myTip('Remove item(s) from selected ones (first mark!)')\" /></a></td>\n"+
			"		<td valign=\"top\">\n";

		

		String autocomplete = "";
		if ( ajaxActionCode == DHTMLConstants.CLASSESBELONGINGTOOM ) {
			
			/* Scriptaculous:	
			String autocomplete = "<style> div.auto_complete {  width: 350px;  background: #fff;}div.auto_complete ul {  border:1px solid #888;  margin:0;  padding:0;  width:100%;  list-style-type:none;}div.auto_complete ul li {  margin:0;  padding:3px;}div.auto_complete ul li.selected {  background-color: #ffb;}div.auto_complete ul strong.highlight {  color: #800;  margin:0;  padding:0;}</style>";
		
			autocomplete += "<input onfocus=\"activateAutocompleter('" + nameFormElement + "_adder','" + nameFormElement + "_received','ScriptaculousAutocompleteClasses' )\" autocomplete=\"off\" id=\"" + nameFormElement + "_adder\" name=\"" + nameFormElement + "_adder\" type=\"text\" value=\"\" />" +
				" <input type=\"button\" value=\"add\" onclick=\"setFormValueFromBrowseWin('" + nameFormElement + "','" + Vocabulary.CLASS_NAMESPACE + "'+document.getElementById('" + nameFormElement + "_adder').value,document.getElementById('" + nameFormElement + "_adder').value );\" />\n" +
				"<div class=\"auto_complete\" id=\"" + nameFormElement + "_received\"></div>\n";
			*//*

			// Ajax4Suggest (self modified):

			String additionalparameters = "type=" + Vocabulary.CLASS + "&actionCode="+DHTMLConstants.SUGGEST;
				
			ret += "<div style=\"width:300px;\"><input style=\"width:240px;\" onkeyup=\"disableButtonOnValueNull('" + nameFormElement + "_receivedId','" + nameFormElement + "_adderbutton');\" onfocus=\"activateAutocompleter(this.id,'" + nameFormElement + "_receivedId','AjaxXmlGenerator','" + additionalparameters+ "',true )\" autocomplete=\"off\" id=\"" + nameFormElement + NAMEFORMELEMENTADDEREXTENSION + "\" name=\"" + nameFormElement + NAMEFORMELEMENTADDEREXTENSION + "\" type=\"text\" value=\"\" onkeypress=\"return noEnter(event)\" />" +
			//			"<img style=\"cursor:pointer;\" src=\"skins/default/images/add.png\" alt=\"add\" title=\"Add\" border=\"0\" onclick=\"javascript:if(document.getElementById('" + nameFormElement + "_receivedId').value=='') { alert('To add a new " + Labels.CLASS.getNameSingular() + " first create one!'); } else { setFormValueFromBrowseWin('" + nameFormElement + "',document.getElementById('" + nameFormElement + "_receivedId').value,document.getElementById('" + nameFormElement + "_adder').value );}\" /></div>";
						" <input id=\"" + nameFormElement + "_adderbutton\" disabled=\"true\"  type=\"button\" value=\"Add\" onclick=\"buttonAddToListClick( '" + nameFormElement + "', '" + nameFormElement + "_receivedId', '"+ nameFormElement + NAMEFORMELEMENTADDEREXTENSION + "', '" + Labels.CLASS.getNameSingular() + "');\" /></div>";
			
			ret += "\n<input type=\"hidden\" id=\"" + nameFormElement + "_receivedId\" name=\"" + nameFormElement + "_receivedId\" value=\"\" />";

			// ret += "\n<div><a href=\"#\" onclick=\"window.location='newClass/?labelEntry='+document.getElementById('" + nameFormElement + "_adder').value; return false;\">Create new " + Labels.CLASS.getNameSingular() +"</a></div>";
			
			
			/* DOJO:
			autocomplete += "<style type=\"text/css\">.choices {    background-color: lavender;    color: black;    border: solid #000000;    border-width: 0px 1px 1px 1px;    font: 10px arial;    display: none;    position: absolute;} .selected {    background-color: #222222;    color: white;    border: solid #CCCCCC;    border-width: 0px 1px 1px 1px;    font: 10px arial;    width: 100%;}</style>";

			autocomplete += "<form id=\"authorForm\">";				
			autocomplete += "<input type=\"text\" name=\"" + nameFormElement + "_adder\" id=\"" + nameFormElement + "_adder\" id=\"author\"/> <input type=\"button\" value=\"add\" onclick=\"setFormValueFromBrowseWin('" + nameFormElement + "','" + Vocabulary.CLASS_NAMESPACE + "'+document.getElementById('" + nameFormElement + "_adder').value,document.getElementById('" + nameFormElement + "_adder').value );\" />\n";
			autocomplete += "<dojo:AutoComplete formId=\"authorForm\"";
			autocomplete += "	   textboxId=\"" + nameFormElement + "_adder\"";
			autocomplete += "	   action=\"DojoAutocompleteClasses\"/>";
			autocomplete += "</form>";
			*//*		
		}
		else if ( ajaxActionCode == DHTMLConstants.PROPERTIESBELONGINGTOOM ) { 
			

			// Ajax4Suggest (self modified):
			String additionalparameters = "type=" + Vocabulary.DATATYPEPROPERTY + "&type=" + Vocabulary.OBJECTPROPERTY + "&actionCode="+DHTMLConstants.SUGGEST;
			
			autocomplete += "<div style=\"width:300px;\"><input style=\"width:240px;\" onkeyup=\"disableButtonOnValueNull('" + nameFormElement + "_receivedId','" + nameFormElement + "_adderbutton');\" onfocus=\"activateAutocompleter(this.id,'" + nameFormElement + "_receivedId','AjaxXmlGenerator','" + additionalparameters+ "',true )\" autocomplete=\"off\" id=\"" + nameFormElement + NAMEFORMELEMENTADDEREXTENSION + "\" name=\"" + nameFormElement + NAMEFORMELEMENTADDEREXTENSION + "\" type=\"text\" value=\"\" onkeypress=\"return noEnter(event)\" /> " +
			//		"<img style=\"cursor:pointer;\" src=\"skins/default/images/add.png\" alt=\"add\" title=\"Add\" border=\"0\" onclick=\"javascript:if(document.getElementById('" + nameFormElement + "_receivedId').value=='') { alert('To add a new " + Labels.PROPERTY.getNameSingular() + " first create one!'); } else { setFormValueFromBrowseWin('" + nameFormElement + "',document.getElementById('" + nameFormElement + "_receivedId').value,document.getElementById('" + nameFormElement + "_adder').value );}\" /></div>";
					" <input id=\"" + nameFormElement + "_adderbutton\" disabled=\"true\"  type=\"button\" value=\"Add\" onclick=\"buttonAddToListClick( '" + nameFormElement + "', '" + nameFormElement + "_receivedId', '"+ nameFormElement + NAMEFORMELEMENTADDEREXTENSION + "', '" + Labels.PROPERTY.getNameSingular() + "');\" /></div>";

			autocomplete += "\n<input type=\"hidden\" id=\"" + nameFormElement + "_receivedId\" name=\"" + nameFormElement + "_receivedId\" value=\"\" />";
			
			// autocomplete += "\n<div><a href=\"#\" onclick=\"window.location='newProperty/?labelEntry='+document.getElementById('" + nameFormElement + "_adder').value; return false;\">Create new " + Labels.PROPERTY.getNameSingular() +"</a></div>";
			
		}

		ret += autocomplete;
		
			
		ret +=
			"		</td>\n"+
			"	</tr>\n"+
			"</table>\n";
		



		// the actual values (again; this field is filled / decreased with DHTML but has to be "initialized")
		ret +=
			"<input type=\"hidden\" name=\"" + nameFormElement + "\" value=\"" + elementEntry + "\" />\n";

		
		return ret;
		
	}
	*/
	

	protected static String getElementsHTMLList( java.util.ArrayList<URI> entry ) {
		
		String ret = "";
		
		if( entry==null ) {
			ret += NOTHINGSELECTED;
		}
		else {

			ret += HelperFunctions.getListOfElements2( entry, Vocabulary.ENGLISH );	
		}
		
		return ret.trim();	
	}
	
	

	
	public static String getVersionStatement( URI uri ) {
		String ret = "";

		URI mostActual = VersioningMapper.getMostActualVersion( uri );
		
		ret += "<div class=\"versionwarning\">";
		ret += "<div class=\"versionwarningtext\">";
		
		ret += "This is an old revision of this page as edited at " + Mapper.selectHasVersionDateTime( uri ) + ". It may differ significantely from " + HelperFunctions.getLinkedLabel( mostActual, "the newest version" ) + ".";

		ret += "</div>";

		URI older = VersioningMapper.selectOlderVersion( uri );
		if( older!=null )
			ret += HelperFunctions.getLinkedLabel( older, "older version" ) + " | ";
		
		URI newer = VersioningMapper.selectNewerVersion( uri );
		if( newer!=mostActual )
			ret += HelperFunctions.getLinkedLabel( newer, "newer version" ) + " | ";		

		ret += HelperFunctions.getLinkedLabel( mostActual, "newest version" );

		ret += "</div>";
		
		return ret;
	}
	

	public static String getOntologiesToImportField( URI id ) {
		String ret = "";
		ret += "<p>\n";

		ArrayList<URI> list = OntologyModuleMapper.selectAll();
		String options = "";	
		for( int i = 0; i < list.size(); i++ ) {
			
			if( !list.get(i).equals( id ) ) {
				
				try {
					String label = Mapper.selectLabel( list.get(i), Vocabulary.ENGLISH );

					options +=
						"	<option value=\""+ list.get(i) +"\">" + label + "</option>";
				}
				catch( Exception e ) {					
					logger.error(e);		
				}
			}
		}
		
		if( options.equals("") ) {
			
			ret += "nothing to select.";			
		}
		else {
			ret += "<select name=\"ontologyModuleToImport\">";			
			ret += options;
			ret += "</select>";
		}
		
		ret += "</p>\n";
		
		return ret;
	}
	

	public static String getButtonInsertPropertyFormSubmit() {

		String ret = "<div style=\"margin: 10px 0px 5px 0px;\">\n";

		String onclick = "return confirm('It is not possible to change " + Labels.RANGE.getNameSingular() + " from Datatypes (i.e. string, boolean, etc.) to "+ Labels.INSTANCE.getNamePlural()+" of a created "+ Labels.PROPERTY.getNameSingular()+". Double-check your input in "+ Labels.RANGE.getNamePlural()+"! \\n\\nDo you want to create the "+Labels.PROPERTY.getNameSingular()+" with the given values now?');";
		String onclick2 = "if( confirm('Close without to save?') ) window.close()";
		
		ret += "<input style=\"cursor:pointer\" title=\"Create\" type=\"image\" name=\"saveclose\" src=\"skins/default/images/accept_big.png\" border=\"0\" alt=\"Create\" onclick=\""+onclick+"\" />";

		ret += "<img style=\"margin-left:10px; cursor:pointer\" title=\"Cancel\" onclick=\""+onclick2+"\" src=\"skins/default/images/cancel_big.png\" border=\"0\" alt=\"Cancel\" />";
		
		ret += "</div>\n";
		return ret;
	}
	
	public static String getButtonInsertFormSubmit() {

		String ret = "<div style=\"margin: 10px 0px 5px 0px;\">\n";

		String onclick = "return true;";
		String onclick2 = "if( confirm('Close without to save?') ) window.close()";
		
		ret += "<input style=\"cursor:pointer\" title=\"Create\" type=\"image\" name=\"saveclose\" src=\"skins/default/images/accept_big.png\" border=\"0\" alt=\"Create\" onclick=\""+onclick+"\" />";

		ret += "<img style=\"margin-left:10px; cursor:pointer\" title=\"Cancel\" onclick=\""+onclick2+"\" src=\"skins/default/images/cancel_big.png\" border=\"0\" alt=\"Cancel\" />";
		
		ret += "</div>\n";
		return ret;
	}
	
	

	/**
	 * 
	 * @param nameFormElement
	 * @param elementEntry
	 * @param typesToSuggest
	 * @param createNewAdditionalParams	This parameters will be sent to the creation-page if the user clicks on "create new ..."
	 * @return
	 */
	protected static String getItemsEditPanel( String nameFormElement, ArrayList<URI> entryList, String viewtype, String createNewAdditionalParams, boolean showCreateLinks  ) {
		
		String ret = "";
		String val = "";
			
		

		ret += "<div id=\"" + nameFormElement + "_act\" >"; // WITHOUT "\n" !!!

		if( entryList!=null ) {
			try {
				// the actual values
				
				Iterator<URI> iter = entryList.iterator();
				while( iter.hasNext() ) {
					URI curr = iter.next();
				
					try {
						URI type = AbstractDataConnector.getType(curr);
						String id = HelperFunctions.getUriForHref( curr );
						
						if(
								type != null && (
								type.equals( Vocabulary.CLASS ) ||
								type.equals( Vocabulary.DATATYPEPROPERTY ) ||
								type.equals( Vocabulary.OBJECTPROPERTY ) ||
								type.equals( Vocabulary.ONTOLOGYMODULE ) ) ) {
							
							String label = Mapper.selectLabel( curr, Vocabulary.ENGLISH );
							String comment = Mapper.selectComment( curr, Vocabulary.ENGLISH );
							
							ret += getSelectedElementHTML( id, label, HelperFunctions.getShortHTMLComment(comment), nameFormElement + "_act", nameFormElement + "_deletebuttonid" ) + " ";
						}

						val += id + HelperFunctions.DEFAULTPLITTER;
					}
					catch( Exception e ) {					
						logger.error(e);			
					}	
					
				}
				
			}
			catch( Exception e )
			{
				logger.error( e );
			}
		}

		ret += "</div>\n";	
		
		


		//ret += "<span id=\""+nameFormElement + "_addbuttonid\" ><a href=\"\" onClick=\"return false;\"><img src=\"skins/default/images/add.png\" style=\"border:none;\" onmouseover=\"myTip('Add new item(s)')\" /></a></span> ";
		
		ret += getDeleteButton(nameFormElement);
		
		
		String additionalparameters = "actionCode="+DHTMLConstants.SUGGEST + "&viewtype=" + viewtype;
		
		String defaultValue = "Search to Add";
		
		// autocomplete += "<div style=\"width:260px;\">";
		// autocomplete += "<input style=\"width:200px;\" onkeyup=\"disableButtonOnValueNull('" + nameFormElement + "_receivedId','" + nameFormElement + "_adderbutton');\" onblur=\"searchboxOnBlur('" + nameFormElement + NAMEFORMELEMENTADDEREXTENSION + "','" + nameFormElement + "_receivedId','" + defaultValue + "')\" onfocus=\"searchboxOnFocus(this,'" + additionalparameters + "','" + nameFormElement + "_receivedId','" + defaultValue + "','true','" + createNewAdditionalParams + "');\" autocomplete=\"off\" id=\"" + nameFormElement + NAMEFORMELEMENTADDEREXTENSION + "\" name=\"" + nameFormElement + NAMEFORMELEMENTADDEREXTENSION + "\" type=\"text\" value=\"" + defaultValue + "\" onkeypress=\"return noEnter(event)\" />" +
		// autocomplete += "</div>";

		ret +=
			"		<div class=\"addcontainer\">\n";
		ret += 
			"			<input class=\"suggestbox\" onkeyup=\"buttonAddToSelectedClick( '" + nameFormElement + "', '" + nameFormElement + "_receivedId', '"+ nameFormElement + NAMEFORMELEMENTADDEREXTENSION + "', '" + Labels.ONTOLOGY.getNameSingular() + "', '"+ nameFormElement +"_act','" + nameFormElement + "_deletebuttonid');\" onblur=\"searchboxOnBlur('" + nameFormElement + NAMEFORMELEMENTADDEREXTENSION + "','" + nameFormElement + "_receivedId','" + defaultValue + "')\" onfocus=\"searchboxOnFocus('" + nameFormElement + NAMEFORMELEMENTADDEREXTENSION + "','" + additionalparameters + "','" + nameFormElement + "_receivedId','" + defaultValue + "'," + (showCreateLinks==true ? "true" : "false") + ",'" + createNewAdditionalParams + "');\" autocomplete=\"off\" id=\"" + nameFormElement + NAMEFORMELEMENTADDEREXTENSION + "\" name=\"" + nameFormElement + NAMEFORMELEMENTADDEREXTENSION + "\" type=\"text\" value=\"" + defaultValue + "\" onkeypress=\"return noEnter(event)\" />";
		ret += 
			"			<input type=\"hidden\" id=\"" + nameFormElement + "_receivedId\" name=\"" + nameFormElement + "_receivedId\" value=\"\" /><br/>";
		ret += 
			"			<div class=\"inputhint\">Input the label of the element to add.</div>\n";
		ret += 
			"		</div>\n";
		
		ret += 
			"	<div class=\"clearer\">&nbsp;</div>\n";
		

		
		
		

		// the actual values (again; this field is filled / decreased with DHTML but has to be "initialized")		
		ret +=
			"<input type=\"hidden\" name=\"" + nameFormElement + "\" value=\"" + val + "\" />\n";

		
		return ret;
	}
	
	/**
	 * 
	 * @param nameFormElement
	 * @param elementEntry
	 * @param typesToSuggest
	 * @param createNewAdditionalParams	This parameters will be sent to the creation-page if the user clicks on "create new ..."
	 * @return
	 */
	protected static String getInstanceEditPanel( String nameFormElement, ArrayList<URI> entryList, String viewtype, String createNewAdditionalParams, boolean showCreateLinks  ) {
		
		String ret = "";
		String val = "";
			
		

		ret += "<div id=\"" + nameFormElement + "_act\" >"; // WITHOUT "\n" !!!

		if( entryList!=null ) {
			try {
				// the actual values
				
				Iterator<URI> iter = entryList.iterator();
				while( iter.hasNext() ) {
					URI curr = iter.next();
				
					try {
						URI type = AbstractDataConnector.getType(curr);
						String id = HelperFunctions.getUriForHref( curr );
						
						if(
								type != null && (
								type.equals( Vocabulary.CLASS ) ||
								type.equals( Vocabulary.DATATYPEPROPERTY ) ||
								type.equals( Vocabulary.OBJECTPROPERTY ) ||
								type.equals( Vocabulary.ONTOLOGYMODULE ) ) ) {
							
							String label = Mapper.selectLabel( curr, Vocabulary.ENGLISH );
							String comment = Mapper.selectComment( curr, Vocabulary.ENGLISH );
							
							ret += getSelectedElementHTML( id, label, HelperFunctions.getShortHTMLComment(comment), nameFormElement + "_act", nameFormElement + "_deletebuttonid" ) + " ";
						}

						val += id + HelperFunctions.DEFAULTPLITTER;
					}
					catch( Exception e ) {					
						logger.error(e);			
					}	
					
				}
				
			}
			catch( Exception e )
			{
				logger.error( e );
			}
		}

		ret += "</div>\n";	
		
		


		//ret += "<span id=\""+nameFormElement + "_addbuttonid\" ><a href=\"\" onClick=\"return false;\"><img src=\"skins/default/images/add.png\" style=\"border:none;\" onmouseover=\"myTip('Add new item(s)')\" /></a></span> ";
		
		ret += getDeleteButton(nameFormElement);
		
		
		String additionalparameters = "actionCode="+DHTMLConstants.SUGGEST + "&viewtype=" + viewtype;
		
		String defaultValue = "Label of the instance";
		
		// autocomplete += "<div style=\"width:260px;\">";
		// autocomplete += "<input style=\"width:200px;\" onkeyup=\"disableButtonOnValueNull('" + nameFormElement + "_receivedId','" + nameFormElement + "_adderbutton');\" onblur=\"searchboxOnBlur('" + nameFormElement + NAMEFORMELEMENTADDEREXTENSION + "','" + nameFormElement + "_receivedId','" + defaultValue + "')\" onfocus=\"searchboxOnFocus(this,'" + additionalparameters + "','" + nameFormElement + "_receivedId','" + defaultValue + "','true','" + createNewAdditionalParams + "');\" autocomplete=\"off\" id=\"" + nameFormElement + NAMEFORMELEMENTADDEREXTENSION + "\" name=\"" + nameFormElement + NAMEFORMELEMENTADDEREXTENSION + "\" type=\"text\" value=\"" + defaultValue + "\" onkeypress=\"return noEnter(event)\" />" +
		// autocomplete += "</div>";

		ret +=
			"		<div class=\"instancecontainer\">\n";
		ret += 
			"			<input  id=\""+nameFormElement + NAMEFORMELEMENTADDEREXTENSION+"\" onkeypress=\"if( getCharacterCode(event)=='13') {buttonAddToSelectedClick( '" + nameFormElement + "', '" + nameFormElement + "_receivedId', '"+ nameFormElement + NAMEFORMELEMENTADDEREXTENSION + "', '" + Labels.ONTOLOGY.getNameSingular() + "', '"+ nameFormElement +"_act','" + nameFormElement + "_deletebuttonid');;return false};\" autocomplete=\"off\" id=\"" + nameFormElement + NAMEFORMELEMENTADDEREXTENSION + "\" name=\"" + nameFormElement + NAMEFORMELEMENTADDEREXTENSION + "\" type=\"text\" value=\"" + defaultValue + "\" onkeypress=\"return noEnter(event)\" />";
		ret += 
			"			<input type=\"hidden\" id=\"" + nameFormElement + "_receivedId\" name=\"" + nameFormElement + "_receivedId\" value=\"\" /><br/>";
		ret += 
			"			<div class=\"inputhint\">Input the label of the instance to add.</div>\n";
		ret += 
			"		</div>\n";
		
		ret += 
			"	<div class=\"clearer\">&nbsp;</div>\n";
		

		
		
		

		// the actual values (again; this field is filled / decreased with DHTML but has to be "initialized")		
		ret +=
			"<input type=\"hidden\" name=\"" + nameFormElement + "\" value=\"" + val + "\" />\n";

		
		return ret;
	}
	
	
	protected static String getDeleteButton( String nameFormElement ) {
		 String ret = "";

		ret += "<div style=\"float:left; margin-right: 5px;\">" +
				"<img id=\""+nameFormElement + "_deletebuttonid\" src=\"skins/default/images/delete_unactive.png\" border=\"\" style=\"border:none; cursor:pointer;\" onmouseover=\"myTip('Remove item(s) from selected ones (first mark!)')\" onClick=\"removeSelectedSpans('" + nameFormElement + "','" + nameFormElement + "_act'); hideDeleteButtonIfNothingSelected('" + nameFormElement + "_act','"+nameFormElement + "_deletebuttonid'); return false\" />" +
				"</div>";
		 
		 return ret; 
	}
	
	// used for flickr and youtube to get the preview.
	protected static String getSelectedElementHTML( String id, String label, String comment, String containerId, String deletebuttonId ){

		comment = StringEscapeUtils.escapeJavaScript( comment );
		label = StringEscapeUtils.escapeHtml( label );
		
		return "<span id=\"" + id + "\" class=\"selectedElement\" onmouseover=\"myTip('"+comment+"');\" onclick=\"toggleBackground(this); hideDeleteButtonIfNothingSelected('"+containerId+"','"+deletebuttonId+"');return false;\">" + label + "</span>"; // WITHOUT "\n" !!!
	}
}
